import { Table, Space, Button, Popconfirm, Modal, Form, Input, Select, Tree, message } from 'antd'
import { useEffect, useMemo, useState } from 'react';
import type { ColumnsType } from 'antd/es/table';
import type { TableRowSelection } from 'antd/es/table/interface';

import {
  EditOutlined,
  DeleteOutlined
} from '@ant-design/icons'

import { addAdmin, getAdminList, IAdminParams, removeAdmin, updateAdmin } from '../../api/admin';
import menus, { IMenuProps } from '../../router/menu';
import { AxiosResponse } from 'axios';
import { useAppSelector } from '../../store/hooks';

type AdminListProps = {}

interface DataType {
  adminid: string;
  adminname: number;
  password: string;
  role: number;
  checkedKeys: any[];
}
interface ITreeData {
  key: string
  title: string
  children?: ITreeData[]
}
function getTreeData (menus: IMenuProps[]) {
  const arr: ITreeData[] = []
  menus.forEach(item => {
    let obj: ITreeData = {
      key: '',
      title: ''
    }
    if (item.children) {
      obj = {
        key: item.keyId,
        title: item.label,
        children: getTreeData(item.children)
      }
    } else {
      obj = {
        key: item.keyId,
        title: item.label,
      }
    }
    arr.push(obj)
  })
  return arr
}

export const AdminList = (props: AdminListProps) => {
  const [adminList, setAdminList] = useState([])
  const [height] = useState(document.body.offsetHeight)

  const [current, setCurrent] = useState(1) // 页码
  const [pageSize, setPageSize] = useState(10) // 每页显示个数


  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      align: 'center',
      render: (text, record, index) => {
        return <span>{ (current - 1) * pageSize +  index + 1}</span>
      }
    },
    {
      title: '账户',
      align: 'center',
      dataIndex: 'adminname'
    },
    {
      title: '角色',
      align: 'center',
      dataIndex: 'role',
      render: text => {
        return text === 2 ? '超级管理员' : '管理员'
      }
    },
    { 
      title: '操作',
      align: 'center',
      render: (text, record, index) => {
        return (
          <Space >
            <Button type="primary" shape="circle" icon={<EditOutlined />} onClick = { () => {
              setType('update')
              setAddAdminVisible(true)
              form.setFieldsValue({
                adminname: record.adminname,
                role: record.role
              })
              console.log('record', record)
              setCheckedKeys(record.checkedKeys)
            }}/>
            <Popconfirm
              title="确定删除吗?"
              onConfirm={ () => {
                removeAdmin({ adminid: record.adminid }).then(() => { // 删除
                  getAdminData() // 重新获取数据 ---- 重置页码以及每页显示个数
                  setCurrent(1)
                  setPageSize(10)
                })
              }}
              onCancel={() => {}}
              okText="确定"
              cancelText="再想想"
            >
              <Button danger shape="circle" icon={<DeleteOutlined />} />
            </Popconfirm>
          </Space>
        )
      }
    }
  ]
  // 数据请求
  const getAdminData = () => { // 封装了数据请求，增删改之后都要运行
    getAdminList().then(res => {
      // console.log(res.data.data)
      setAdminList(res.data.data)
    })
  }
  useEffect(() => {
    getAdminData()
  }, [])

  const [type, setType] = useState('add') // update

  // 添加管理员
  const [form] = Form.useForm(); // 函数式组件用法 https://ant-design.gitee.io/components/form-cn/#components-form-demo-control-hooks
  const [addAdminVisible, setAddAdminVisible]= useState(false)
  const treeData = getTreeData(menus) // 获取菜单项数据
  const [checkedKeys, setCheckedKeys] = useState(['0-0'])
  console.log(checkedKeys)
  const onAdd = (values: IAdminParams) => {
    values.checkedKeys = checkedKeys // 追加数据，一定要注意大小写，数据库中checkedkeys
    console.log(values)
    addAdmin(values).then(() => {
      // 模态框消失 ， 重置表单
      form.setFieldsValue({
        adminname: '', password: '', role: 1
      })
      setCheckedKeys(['0-0'])
      setAddAdminVisible(false)
      getAdminData()
    })
  }
  // 更新
  const onUpdate = (values: IAdminParams) => {
    values.checkedKeys = checkedKeys
    updateAdmin(values).then(() => {
      form.setFieldsValue({
        adminname: '', password: '', role: 1
      })
      setCheckedKeys(['0-0'])
      setAddAdminVisible(false)
      getAdminData()
    })
  }
  // 批量删除数据
  const [selectedRowKeys, setSelectedRowKeys] = useState([]); // 选中需要删除的数据
  const onSelectChange = (newSelectedRowKeys: any) => { // 点击选中时的数据事件
    setSelectedRowKeys(newSelectedRowKeys)
  }
  const rowSelection: TableRowSelection<DataType> = { // 最左侧选择框选项
    selectedRowKeys,
    onChange: onSelectChange
  };

  const showDeleteMoreBtn = useMemo(() => { // 计算属性 有选中则出现批量删除，没有选中 则不出现
    return selectedRowKeys.length
  }, [selectedRowKeys])

  const role = useAppSelector(state => state.user.role)

  console.log('selectedRowKeys', selectedRowKeys)
  // console.log('showDeleteMoreBtn', showDeleteMoreBtn)
  return (
    <Space direction='vertical' style={{ width: '100%'}}>
      <Space>
        <Button type="primary" onClick={ () => {
          setType('add')
          setAddAdminVisible(true)
        } }>添加管理员</Button>
        { 
          showDeleteMoreBtn > 0 ? <Button type="primary" onClick={ () => {

          if (role < 2) {
            message.warning('暂无权限')
            return
          }
          // 保证所有的数据删除之后再刷新视图
          // 保证所有的数据都操作完，第一时间想到的是 Promise.all()
          // Promise.all 方法中参数为一个数组，数组的元素的返回值都基于 promise
          // 一个页面5给请求，保证都请求完成之后操作,请求结果 分别对应前面的5各请求
          // Promise.all([请求1， 请求2， 请求3，请求4，请求5]).then(result=> {})
          const removeArr: AxiosResponse<any, any>[] = []
          selectedRowKeys.forEach(async item => {
            removeArr.push(await removeAdmin({ adminid: item }))
          })
          Promise.all(removeArr).then((res) => {
            console.log('result', res)
            getAdminData()
          })
        } }>批量删除</Button> : null }
      </Space>
      <Table 
        dataSource={ adminList } 
        columns = { columns } 
        rowKey = 'adminid'
        bordered
        scroll={ { y: height - 330 } }
        pagination = {{
          position: ['bottomRight'],
          current,
          pageSize,
          onChange: (page, pageSize) => {
            setCurrent(page)
            setPageSize(pageSize)
          },
          showTotal: (total) => {
            return <span>共有{total}条数据</span>
          },
          showQuickJumper: true,
          pageSizeOptions: [5, 10, 20, 50]
        }}
        rowSelection={rowSelection}
        />
      <Modal 
        title= { type === 'add' ? "添加管理员" : "更新管理员信息"} 
        visible={ addAdminVisible }
        footer = { null }
        onCancel={ () => {
          form.setFieldsValue({
            adminname: '', password: '', role: 1
          })
          setCheckedKeys(['0-0'])
          setAddAdminVisible(false)
        } }
      >
        <Form form = { form }  name="dynamic_rule" onFinish={ type === 'add' ? onAdd : onUpdate } initialValues = {{ role: 1}}>
          <Form.Item
            name="adminname"
            label="管理员账户"
            rules={[
              {
                required: true,
                message: '请输入管理员账户',
              },
            ]}
          >
            <Input placeholder="管理员账户" disabled = { type === 'update'}/>
          </Form.Item>
          {
            type === 'update' ? null : <Form.Item
            name="password"
            label="管理员密码"
            rules={[
              {
                required: true,
                message: '请输入管理员初始密码',
              },
            ]}
          >
            <Input type="password" placeholder="密码" />
          </Form.Item>
          }
          <Form.Item
            name="role"
            label="管理员角色"
            rules={[
              {
                required: true,
              },
            ]}
          >
            <Select >
              <Select.Option value={1}>管理员</Select.Option>
              <Select.Option value={2}>超级管理员</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="checkedkeys"
            label="管理员权限"
          >
            <Tree 
              checkable
              defaultExpandAll
              checkedKeys = { checkedKeys }
              treeData = { treeData }
              onCheck = { (checkedKeys: any) => { return setCheckedKeys(checkedKeys);}}
            />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              { type === 'add' ? '添加' : '更新' }
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </Space>
  );
}